/**
 * Created by liuhe on 2016/11/30.
 */
('use strict');

//引入model
import * as mongoose from 'mongoose';
import GlobalSetupModel from '../dao/globalSetup/global-setup-model';
import BusinessConfigService from './business-config-service';
import * as Immutable from 'immutable';

//默认数据
let defaultGlobalSetup = Immutable.fromJS({
  //站点设置 全局的,title seo icon
  siteTitle: '',
  siteIconImgSrc: 'https://qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/public/img/editLeftNav/blank_icon.png',
  host: {
    pc: '',
    weixin: '',
    api_host: ''
  },
  platformInfo: {
    pc: {
      logo: 'https://qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/public/img/x-stie.png'
    },
    weixin: {
      logo: 'https://qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/public/img/x-stie.png'
    },
    app: {
      logo: 'https://qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/public/img/x-stie.png'
    },
    pad: {
      logo: 'https://qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/public/img/x-stie.png'
    }
  }
});
const defaultSiteTitle = {
  d2p: '我的订货',
  d2cStore: '我的商城',
  ehome: '我的家政'
};

export default class GlobalSetupService {
  /**
     * type 实例方法
     * 获取globalSetup 进入到编辑页 ，页面管理页面，选择模板页面需要获取全量globalSetup数据
     * @param uid         用户ID
     * @param systemCode  业务线标示
     * @returns {Promise}
     */
  static async getGlobalSetup({ uid, systemCode }) {
    let globalSetup: any = await GlobalSetupService.getGlobalSetupFromDB({ uid, systemCode });
    if (!globalSetup) {
      globalSetup = defaultGlobalSetup.toJS();
      globalSetup.uid = uid;
      globalSetup.systemCode = systemCode;
      globalSetup.siteTitle = defaultSiteTitle[systemCode] ? defaultSiteTitle[systemCode] : '我的站点';
      //将数据保存如数据库
      await GlobalSetupService.saveGlobalSetup2DB(globalSetup);
    }
    //数据兼容
    if (globalSetup && !globalSetup.platformInfo) {
      globalSetup.platformInfo = {};
    }
    return globalSetup;
  }

  static async getSiteId({ uid, systemCode }) {
    let id = await new Promise((resolve, reject) => {
      GlobalSetupModel.findOne({ uid, systemCode }).select('_id').lean().exec((err, data: any) => {
        err ? reject(err) : resolve((data && data._id) || null);
      });
    });
    if (!id) {
      let globalSetup = defaultGlobalSetup.toJS();
      globalSetup.uid = uid;
      globalSetup.systemCode = systemCode;
      globalSetup.siteTitle = defaultSiteTitle[systemCode] ? defaultSiteTitle[systemCode] : '我的站点';
      //将数据保存如数据库
      id = await GlobalSetupService.saveGlobalSetup2DB(globalSetup);
      await BusinessConfigService.initConfigInfo(id);
    }
    return id;
  }

  /**
     * 从数据库获取globalSetup
     * @param uid
     * @param systemCode
     * @returns {Promise}
     */
  static getGlobalSetupFromDB({ uid, systemCode }) {
    return new Promise((resolve, reject) => {
      GlobalSetupModel.findOne({ uid, systemCode }).select('-sitemanager').lean().exec(function(err, data) {
        err ? reject(err) : resolve(data);
      });
    });
  }

  /**
     * 保存数据到数据库
     * @param globalSetup
     * @returns {Promise}
     */
  static saveGlobalSetup2DB(globalSetup) {
    return new Promise((resolve, reject) => {
      new GlobalSetupModel(globalSetup).save((err, data) => {
        err ? reject(err) : resolve(data._id);
      });
    });
  }

  /**
     * 保存数据到数据库 有则改之 无则加之
     * @param globalSetup
     * @returns {Promise}
     */
  static upsertGlobalSetup(globalSetup) {
    let { uid, systemCode } = globalSetup;
    let target = { uid, systemCode };
    delete globalSetup._id;
    delete globalSetup.__v;
    return new Promise((resolve, reject) => {
      GlobalSetupModel.update(target, globalSetup, {
        upsert: true
      }).exec(function(err, data) {
        err ? reject(err) : resolve(data);
      });
    });
  }

  /**
   * 获取globalSetup中的指定信息
   * eg  path = 'siteTitle siteIconImgSrc host.pc'  return {siteTitle:xx ,siteIconImgSrc:xx , host.pc:xx }
   * @param id
   * @param uid
   * @param systemCode
   * @param path
   * @returns {Promise<T>}
   */
  static getSiteInfo({
    id,
    uid,
    systemCode,
    path
  }: {
    id?: string;
    uid?: string;
    systemCode?: string;
    path: string;
  }): any {
    return new Promise((resolve, reject) => {
      let query = mongoose.Types.ObjectId.isValid(id)
        ? GlobalSetupModel.findById(id)
        : GlobalSetupModel.findOne({ uid, systemCode });
      query.select(path).lean().exec((err, data) => {
        if (err) {
          reject(err);
        } else {
          let result = {};
          let siteInfo = Immutable.fromJS(data);
          let targetArr = path.split(' ');
          for (let i = 0, len = targetArr.length; i < len; i++) {
            let target = targetArr[i];
            let targetPath = target.split('.');
            let targetValue = siteInfo.getIn(targetPath);
            result[target] = targetValue && targetValue.toJS ? targetValue.toJS() : targetValue;
          }
          resolve(result);
        }
      });
    });
  }

  /**
     * 全量更新页面信息 发布页面的时候 包括用户icon和title的同步修改
     * @param id
     * @param uid
     * @param systemCode
     * @param siteInfo
     * @returns {Promise}
     */
  static updateSiteInfo({
    id,
    uid,
    systemCode,
    siteInfo
  }: {
    id?: string;
    uid?: string;
    systemCode?: string;
    siteInfo: any;
  }) {
    return new Promise((resolve, reject) => {
      mongoose.Types.ObjectId.isValid(id)
        ? GlobalSetupModel.findByIdAndUpdate(id, { $set: siteInfo }).exec((err, data) => {
            err ? reject(err) : resolve(data);
          })
        : GlobalSetupModel.findOneAndUpdate({ uid, systemCode }, { $set: siteInfo }).exec((err, data) => {
            err ? reject(err) : resolve(data);
          });
    });
  }

  static async getUsersList({ systemCode, uid, pageNum, pageSize }) {
    pageNum = parseInt(pageNum, 10);
    pageSize = parseInt(pageSize, 10);

    let target: any = { systemCode };
    if (uid) {
      let uidArr = [];
      uid.split(',').forEach((curId, index) => {
        curId = curId.trim();
        if (curId) {
          uidArr.push(curId);
        }
      });
      target.uid = { $in: uidArr };
    }

    let totalCount = await new Promise((resolve, reject) => {
      GlobalSetupModel.count(target, function(err, data) {
        err ? reject(err) : resolve(data);
      });
    });

    let usersList: any = [];

    if (pageNum > 0) {
      let index = pageNum * pageSize;
      let item: any = await new Promise((resolve, reject) => {
        GlobalSetupModel.aggregate([
          { $match: target },
          { $limit: index },
          { $sort: { _id: -1 } },
          { $limit: 1 }
        ]).exec(function(err, data) {
          err ? reject(err) : resolve(data.length > 0 ? data[0] : null);
        });
      });
      let objectId = item && item._id;
      usersList = await new Promise((resolve, reject) => {
        target._id = { $gt: objectId };
        GlobalSetupModel.find(target).select('-sitemanager').limit(pageSize).exec((err, data) => {
          err ? reject(err) : resolve(data);
        });
      });
    } else {
      //第一页数据仍然用skip
      usersList = await new Promise((resolve, reject) => {
        GlobalSetupModel.find(target)
          .select('-sitemanager')
          .skip(pageNum * pageSize)
          .limit(pageSize)
          .exec((err, data) => {
            err ? reject(err) : resolve(data);
          });
      });
    }
    return { totalCount, usersList };
  }

  static getAllGlobalSetupCount({ systemCode, uid }) {
    let target: any = { systemCode };
    if (uid) {
      let uidArr = [];
      uid.split(',').forEach((curId, index) => {
        curId = curId.trim();
        if (curId) {
          uidArr.push(curId);
        }
      });
      target.uid = { $in: uidArr };
    }
    return new Promise((resolve, reject) => {
      GlobalSetupModel.count(target, function(err, data) {
        err ? reject(err) : resolve(data);
      });
    });
  }
}
